﻿using Microsoft.IdentityModel.Tokens;
using SmartAgricultureService.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace SmartAgricultureService.Core
{
    public sealed class JwtContext
    {
        private readonly SymmetricSecurityKey secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppConfiguration.Jwt.SecretKey));
        public string CreateToken(string name, string email, string role)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var claims = new[] { new Claim(ClaimTypes.Role, role), new Claim(ClaimTypes.Name, name), new Claim(ClaimTypes.Email, email) };
                var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
                var jwtSecurityToken = new JwtSecurityToken(AppConfiguration.Jwt.Issuer, AppConfiguration.Jwt.Audience, claims, DateTime.Now, DateTime.Now.AddDays(7), signingCredentials);
                return tokenHandler.WriteToken(jwtSecurityToken);
            }
            catch (Exception ex)
            {
                Logger.Instance.LogError("CreateToken", ex);
                return string.Empty;
            }
        }
        public bool IsExpired(string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = secretKey,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);
                return validatedToken.ValidTo < DateTime.UtcNow;
            }
            catch (Exception ex)
            {
                Logger.Instance.LogError("IsExpired", ex);
                return true;
            }
        }
        public bool IsRoleAt(string token, string roleName)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var claimsPrincipal = tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = secretKey,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ClockSkew = TimeSpan.Zero
                }, out _);
                return claimsPrincipal.HasClaim(ClaimTypes.Role, roleName);
            }
            catch (Exception ex)
            {
                Logger.Instance.LogError("IsExpired", ex);
                return false;
            }
        }
    }
}